package com.motong.gongdan.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.motong.gongdan.config.ResponseData;
import com.motong.gongdan.config.auth.UserLoginToken;
import com.motong.gongdan.entity.CustomField;
import com.motong.gongdan.entity.MobileCardConf;
import com.motong.gongdan.enums.ObjectType;
import com.motong.gongdan.service.CustomFieldService;
import com.motong.gongdan.service.MobileCardConfService;
import com.motong.gongdan.util.ColumnUtils;
import com.motong.gongdan.util.LoginUtil;
import com.motong.gongdan.vo.system.CardConfController.query.DetailQuery;
import com.motong.gongdan.vo.system.CardConfController.query.EditQuery;
import com.motong.gongdan.vo.system.CardConfController.vo.ColumnDropDownVo;
import com.motong.gongdan.vo.system.CardConfController.vo.ColumnVo;
import com.motong.gongdan.vo.system.CardConfController.vo.DetailVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Api(tags = "移动端卡片设置")
@RestController
@RequestMapping("/sys/cardConf")
public class CardConfController {

    @Resource
    private MobileCardConfService mobileCardConfService;

    @Resource
    private CustomFieldService customFieldService;


    @UserLoginToken
    @PostMapping("/columnDropDown/{moduleName}")
    @ApiOperation("获取模块字段下拉（columns 字段下拉  pictureColumns 封面下拉）")
    public ResponseData<ColumnDropDownVo> columnDropDown(@PathVariable(required = false, value = "moduleName") String moduleNames) {
        moduleNames = Objects.isNull(moduleNames) ? "workOrder" : moduleNames;
        List<String> moduleList = Arrays.stream(moduleNames.split(",")).filter(StringUtils::hasLength).collect(Collectors.toList());

        List<ColumnVo> columns = new ArrayList<>();
        List<ColumnVo> pictureColumns = new ArrayList<>();
        // 排除元素
        List<String> excludeColumn = Arrays.asList("序号", "生产进度", "创建人", "创建时间", "客户名称", "报工时长", "修改人", "修改时间", "备注", "实际数", "子工艺路线");
        List<String> excludeCuColumnType = Collections.singletonList("upload");
        List<String> missionExcludeColumnName = Arrays.asList("工单编号", "产品信息", "产品编号", "产品名称", "产品规格", "单位");
        // 所需所有自定义字段并过滤(任务的自定义字段为工序的)
        List<CustomField> customFieldList = new ColumnUtils(customFieldService, moduleNames.replace("mission", "processes")).getCustomFieldList().stream().filter(i -> !excludeCuColumnType.contains(i.getFieldType())).collect(Collectors.toList());
        Map<String, List<ColumnVo>> groupByModuleNames = customFieldList.stream().map(i -> new ColumnVo().setCnName(i.getChineseName() + "(" + ObjectType.getDescByCode(i.getFieldAscription()) + ")").setColumnModule(i.getFieldAscription()).setFieldType(i.getFieldType())).collect(Collectors.groupingBy(ColumnVo::getColumnModule));
        //整合列中文名并过滤
        moduleList.forEach(i -> {
            List<String> cnNames = ColumnUtils.BASE_COLUMN_CN_LIST.getOrDefault(i, Collections.emptyList()).stream().filter(d -> !excludeColumn.contains(d)).collect(Collectors.toList());
            List<ColumnVo> baseColumns = cnNames.stream().map(d -> new ColumnVo().setCnName(d).setColumnModule(i)).collect(Collectors.toList());
            if ("workOrder".equals(i) && moduleList.size() > 1) {
                baseColumns = baseColumns.stream().filter(d -> missionExcludeColumnName.contains(d.getCnName())).collect(Collectors.toList());
            }
            if ("mission".equals(i)) {
                baseColumns = baseColumns.stream().filter(d -> !missionExcludeColumnName.contains(d.getCnName())).collect(Collectors.toList());
            }
            columns.addAll(baseColumns);
            if ("workOrder".equals(i)&&moduleList.size() == 1){
                columns.add(new ColumnVo().setCnName("产品信息").setColumnModule(i));
                columns.add(new ColumnVo().setCnName("工单进度").setColumnModule(i));
                columns.add(new ColumnVo().setCnName("计划时间").setColumnModule(i));
                columns.add(new ColumnVo().setCnName("实际时间").setColumnModule(i));
            }
            if ("mission".equals(i)&&moduleList.size() > 1){
                columns.add(new ColumnVo().setCnName("产品信息").setColumnModule(i));
            }
            List<ColumnVo> cuColumnVoList = groupByModuleNames.getOrDefault("mission".equals(i) ? "processes" : i, Collections.emptyList());
            columns.addAll(cuColumnVoList);
            pictureColumns.addAll(cuColumnVoList.stream().filter(d -> "picture".equals(d.getFieldType())).collect(Collectors.toList()));
        });
        return ResponseData.success(new ColumnDropDownVo().setColumns(columns).setPictureColumns(pictureColumns));
    }

    @UserLoginToken
    @PostMapping("/detail")
    @ApiOperation("移动端卡片详情")
    public ResponseData<DetailVo> detail(@RequestBody(required = false) DetailQuery detailQuery) {
        detailQuery = Objects.isNull(detailQuery) ? new DetailQuery() : detailQuery;
        LambdaQueryWrapper<MobileCardConf> mobileCardConfQW = new LambdaQueryWrapper<MobileCardConf>().eq(MobileCardConf::getBelongModule, detailQuery.getBelongModule())
                .eq(Objects.nonNull(detailQuery.getType()), MobileCardConf::getType, detailQuery.getType())
                .orderByAsc(MobileCardConf::getSort);
        List<MobileCardConf> oriData = mobileCardConfService.list(mobileCardConfQW);
        oriData.forEach(i -> i.setCnName(i.getCnName() + (Objects.nonNull(i.getEnName()) ? "" : "(" + ObjectType.getDescByCode(i.getColumnModule()) + ")")));
        DetailVo detailVo = new DetailVo();
        Map<Integer, List<MobileCardConf>> groupByTypesData = oriData.stream().collect(Collectors.groupingBy(MobileCardConf::getType));
        if (Objects.nonNull(groupByTypesData)) {
            detailVo.setTitleValues(groupByTypesData.getOrDefault(0, Collections.emptyList()).stream().map(MobileCardConf::getCnName).collect(Collectors.toList()));
            detailVo.setCoverValue(Objects.isNull(groupByTypesData.get(1)) ? null : groupByTypesData.get(1).get(0).getCnName());
            detailVo.setColumnValues(groupByTypesData.getOrDefault(2, Collections.emptyList()).stream().map(MobileCardConf::getCnName).collect(Collectors.toList()));
        }
        return ResponseData.success(detailVo);
    }


    @UserLoginToken
    @PostMapping("/edit")
    @ApiOperation("添加或修改")
    public ResponseData<?> edit(@RequestBody EditQuery editQuery) {
        // 删除，进行全量编辑
        mobileCardConfService.remove(new LambdaQueryWrapper<MobileCardConf>().eq(MobileCardConf::getBelongModule, editQuery.getBelongModule()));
        AtomicReference<Integer> currentIndex = new AtomicReference<>(0);
        List<MobileCardConf> mobileCardConfigs = new ArrayList<>();
        // 组装保存的数据
        this.assembleData(mobileCardConfigs, 0, currentIndex, editQuery.getTitles(), editQuery.getBelongModule());
        if (Objects.nonNull(editQuery.getCover())) {
            this.assembleData(mobileCardConfigs, 1, currentIndex, Collections.singletonList(editQuery.getCover()), editQuery.getBelongModule());
        }
        this.assembleData(mobileCardConfigs, 2, currentIndex, editQuery.getColumns(), editQuery.getBelongModule());
        mobileCardConfService.saveBatch(mobileCardConfigs);
        return ResponseData.success("编辑成功!");
    }

    @UserLoginToken
    @PostMapping("/delete/{belongModule}")
    @ApiOperation("删除")
    public ResponseData<?> delete(@PathVariable(required = false, value = "belongModule") Integer belongModule) {
        belongModule = Objects.isNull(belongModule) ? 0 : belongModule;
        // 删除，进行全量编辑
        mobileCardConfService.remove(new LambdaQueryWrapper<MobileCardConf>().eq(MobileCardConf::getBelongModule, belongModule));
        return ResponseData.success("删除成功!");
    }


    /**
     * 组装数据
     *
     * @param mobileCardConfigs 组装后的容器
     * @param type              卡片元素类型(0 标题 1 封面 2 元素)
     * @param sort              排序
     * @param columnVos         原数据
     */
    private void assembleData(List<MobileCardConf> mobileCardConfigs, Integer type, AtomicReference<Integer> sort, List<ColumnVo> columnVos, Integer belongModule) {
        // 所有固定字段
        Map<String, Map<String, String>> baseColumnCnEnMap = ColumnUtils.BASE_COLUMN_CN_EN_MAP;
        Integer loginUserId = LoginUtil.getLoginUserId();
        List<String> virtualColumn = Arrays.asList("产品信息", "工单进度", "实际时间", "计划时间");
        if (Objects.nonNull(columnVos) && !columnVos.isEmpty()) {
            columnVos.forEach(i -> {
                String oriCnName = i.getCnName().substring(0, i.getCnName().contains("(") ? i.getCnName().indexOf("(") : i.getCnName().length());
                MobileCardConf mobileCardConf = new MobileCardConf()
                        .setSort(sort.getAndSet(sort.get() + 1)).setBelongModule(belongModule).setType(type).setColumnModule(i.getColumnModule())
                        .setCnName(oriCnName).setEnName(virtualColumn.contains(oriCnName) ? "virtualColumn" : baseColumnCnEnMap.get(i.getColumnModule()).get(oriCnName)).setCreateTime(new Date()).setCreateUser(loginUserId);
                mobileCardConfigs.add(mobileCardConf);
            });
        }
    }


}
